import { createWebHistory, createRouter } from "vue-router"
import { getToken,getUserInfo } from '@/utils/auth'

const routes = [
    {
        path: '/login',
        name: "login",
        component: () => import("../components/login/Login.vue")
    },
    {
        path: "/",
        name: 'Layout',
        component: () => import("../components/MainLayout.vue"),
        // 嵌套路由
        children: [
            {
                // 这里不设置值，是把main作为默认页面
                path: "/",
                redirect: '/home'
            },
            {
                // 这里不设置值，是把main作为默认页面
                path: "home",
                name: "Main",
                component: () => import("../components/Main.vue"),
            },
            {
                path: "user",
                name: "User",
                component: () => import("../components/User.vue"),
            },
            {
                //学院管理
                path: "department",
                name: "Department",
                component: () => import("../components/department/Department.vue"),
            }, {
                //专业管理
                path: '/major',
                name: 'Major',
                component: () => import('@/components/major/Major.vue'), // 确保路径正确
                meta: {
                title: '专业管理'
            }},
            {
                //教师
                path: "teacher",
                name: "Teacher",
                component: () => import("../components/teacher/Teacher.vue"),
            },
            {
                //班级管理
                path: "classs",
                name: "Classs",
                component: () => import("../components/teacher/Classs.vue"),
            },
            {
                //课程管理
                path: "courses",
                name: "Courses",
                component: () => import("../components/course/Courses.vue"),
            },
            {
                path: "rights",
                name: "Rights",
                component: () => import("../components/power/Rights.vue"),
            },
            {
                path: "roles",
                name: "Roles",
                component: () => import("../components/power/Roles.vue"),
                meta:{title:'角色列表',requiresAuth:true,roles:[1,2]}
            },
            {
                path:"student",
                name:"Student",
                component:()=>import("../components/student/Student.vue")
            },
        ],
    },
];

const router = createRouter({
    // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
    history: createWebHistory("/"),
    routes, // `routes: routes` 的缩写
});


// //导航守卫
// //进行路由拦截：当没有登陆标识，直接打回登陆页面，如何避免退回到 登陆页呢？
// // 新增获取 Cookie 的辅助函数
// function getCookie(name) {
//     const value = `; ${document.cookie}`
//     const parts = value.split(`; ${name}=`)
//     if (parts.length === 2) return parts.pop().split(';').shift()
//     return null
//   }
  
//   // 修改导航守卫
//   router.beforeEach((to, from, next) => {
//     if (to.path === '/login') {
//       next()
//     } else {
//       // 直接检查 authToken Cookie
//       const token = getCookie('authToken')
//       if (token) {
//         next()
//       } else {
//         next('/login')
//       }
//     }
//   })
// 全局前置守卫
router.beforeEach((to, from, next) => {
  const hasToken = getToken()
  const userInfo = getUserInfo()
  
  if (hasToken) {
    if (to.path === '/login') {
      // 已登录且要跳转的页面是登录页，则重定向到首页
      next({ path: '/home' })
    } else {
        // 检查是否需要角色权限
        if (to.meta.roles && to.meta.roles.length > 0) {
            if (!to.meta.roles.includes(userInfo.roleId)) {
                next({ path: '/' }) // 没有权限，重定向到首页
            return
         }
        }

      next()
    }
  } else {
    // 未登录可以访问白名单页面，其他页面重定向到登录页
    if (to.path === '/login') {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`)
    }
  }
})

export default router;
